from django.shortcuts import render, redirect
# Create your views here.
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from meiduo_project.utils.response_code import RETCODE
import logging
from oauth.models import OAuthQQUser
from django.contrib.auth import login
from django.urls import reverse
from oauth.utils.utils import generate_access_token,check_access_token
import re
from django_redis import get_redis_connection
from meiduo_project.settings.VerificationSite import SMS_Verification
from users.models import User


logger = logging.getLogger("django")


class QQAuthUserView(View):
    def post(self, request):
        """美多商城用户绑定到openid"""
        # 获取数据
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        access_token = request.POST.get('access_token')

        # 校验数据
        # 判断参数是否齐全
        if not all([mobile, pwd, sms_code_client]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断验证码
        if SMS_Verification == 1:
            # 判断验证码是否正确
            redis_conn = get_redis_connection('verify_code')
            sms_code_server = redis_conn.get('sms_%s'%mobile)
            if sms_code_server is None:
                return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
            if sms_code_client != sms_code_server.decode():
                return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 判断openid是否有效：错误提示放在sms_code_errmsg位置
        openid = check_access_token(access_token)
        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        # 查询手机号是否存在，进行注册保存数据

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoseNotExist:
            # 如果用户不存在，直接注册
            user = User.objects.create_user(username=mobile, password=pwd, mobile=mobile)
        else:
            # 如果用户存在，检验密码，插入数据
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 将用户绑定openid
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            logger.error(e)
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        # 实现状态保持
        login(request, user)

        # 响应绑定结果
        next = request.GET.get('state')
        response = redirect(next)

        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response

    def get(self, request):
        code =request.GET.get("code")
        if not code:
            return http.HttpResponseForbidden("获取code失败")

        # 使用code获取token
        # 创建OAuthQQ工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            # 通过AuthorizationCode获取AccessToken
            access_token = oauth.get_access_token(code)

            # 通过AccessToken获取OpenID
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden("QQ工具认证失败")

        # 通过OpenID判断该用户是否绑定过美多商城的用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid =openid)
        except OAuthQQUser.DoesNotExist:
            access_token_openid = generate_access_token(openid)
            context = {'access_token_openid': access_token_openid}
            return render(request, 'oauth_callback.html', context)
        else:
            login(request, oauth_user.user)
            # 重定向的页面
            response = redirect(reverse('contents:index'))
            # 实现登录后用户名展示，将用户名存在cookie
            response.set_cookie('username', oauth_user.user.username, max_age=3600 * 24 * 15)

            # 响应登录结果，重定向首页
            return response



class QQAuthURLView(View):
    """提供QQ登录扫码页面"""
    def get(self, request):
        next = request.GET.get("next")

        # 创建OAuthQQ工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)


        url = oauth.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': "成功", "login_url": url})
